using System;
using System.ComponentModel;
using System.Threading;
using GeneralDFS.BusinessLogical.Nodes;

namespace GeneralDFS.BusinessLogical.RemoteObject
{
    public partial class NameNodeRemoteObject
    {
        /// <summary>
        /// Maintenance task to stabilize the local node's predecessor as per the Chord paper.
        /// </summary>
        /// <param name="sender">The backgroundworker thread that this task is running on.</param>
        /// <param name="ea">Args (ignored)</param>
        private void StabilizePredecessors(object sender, DoWorkEventArgs ea)
        {
            var me = (BackgroundWorker)sender;

            while (!me.CancellationPending)
            {
                if (this.Predecessor != null)
                {
                    try
                    {
                        // validate predecessor (in case of error, predecessor becomes null
                        // and is fixed by stabilizesuccessors and notify.
                        var instance = NameNode.GetInstance(this.Predecessor);
                        if (!NameNode.IsInstanceValid(instance))
                        {
                            this.Predecessor = null;
                        }
                    }
                    catch (Exception e)
                    {
                        LogUtil.LogInfo("StabilizePredecessors error: {0}", e.Message);
                        this.Predecessor = null;
                    }

                }

                // TODO: make this configurable either via config file or passed in via arguments.
                Thread.Sleep(100);
            }
        }
    }
}
